//广告管理
import moment from "moment";
import {
  Input,
  Select,
  Button,
  Table,
  Space,
  Radio,
  Modal,
  message,
} from "antd";
import { useEffect, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import "../../componet/SystemManeger/Advertisement.css";
import { useNavigate } from "react-router-dom";
import axios from "../../utils/myAixos";
const Advertisement = () => {
  //删除数组的下标
  const [idArr, setIdarr] = useState([]);
  //删除的数据
  const [delDates, setDelDates] = useState({});
  //删除的模态框
  const [messageApi, contextHolder] = message.useMessage();
  const [isModalOpen, setIsModalOpen] = useState(false);
  //用于删除传递数据
  const [delArrId, setDelArrId] = useState("");
  const handleOk = () => {
    // console.log(delArrId)
    let arr = [...dataList];
    for (let i = 0; i <= arr.length - 1; i++) {
      if (arr[i].id === delArrId) {
        arr.splice(i, 1);
      }
    }
    console.log(idArr);
    if (idArr.length > 1) {
      messageApi.info("所选数据不能超过一条!");
    } else {
      axios({
        url: "/adDel",
        method: "post",
        data: {
          idArr: idArr,
        },
      })
        .then((res) => {
          console.log(res);
          if (res.status === 200) {
            console.log(11111);
            messageApi.info("删除成功!");
          } else {
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }

    setDateList(arr);
    setIsModalOpen(false);
    // setIsSuccessModalOpen(true);
  };
  message.config({
    top: 500,
    duration: 2,
    maxCount: 3,
    rtl: true,
    prefixCls: "my-message",
  });
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //上方输入框和下拉框
  const [inputValue, setInputValue] = useState("");
  const [swiper, setSwiper] = useState("");
  const [times, setTimes] = useState("");
  const swiperChange = (value) => {
    setSwiper(value);
  };
  const timeChange = (value) => {
    setTimes(value);
  };
  const changeInput = (value) => {
    setInputValue(value.target.value);
  };
  const[datas,setdatas]=useState([])
  //获取所有淑
const getAllDate=()=>{
  setDateList(datas)
}
  const searchDate = () => {
    setInputValue("")
    console.log(datas,"datas")
    setDateList(datas)
    console.log(dataList,"datalist")
    console.log(swiper);
    console.log(times);
    console.log(inputValue);
    let arrDate = [...dataList];
    arrDate=[...datas]
    const newTitle = [];
    const newClass = [];
    let newTime = [];
    for (let i = 0; i <= arrDate.length - 1; i++) {
      if (arrDate[i].title === inputValue) {
        newTitle.push(arrDate[i]);
      }
    }
    if (newTitle.length === 0) {
      messageApi.info("暂无该条数据!");
    //  setDateList(arrDate)
    } else {
      for (let i = 0; i <= newTitle.length - 1; i++) {
        if (newTitle[i].position === swiper) {
          newClass.push(newTitle[i]);
        }
      }
    }
    console.log(newTitle);
    console.log(newClass);
    // console.log(newTitle)
    for (let i = 0; i <= newClass.length - 1; i++) {
      let startDate = moment(newClass[i].startTime);
      let endDate = moment(new Date());
      let workDayCount = endDate.diff(startDate, "days");
      console.log(workDayCount)
      if (times === "一天内"&&workDayCount===1||workDayCount===0) {
              newTime.push(newClass[i])
                console.log("1")
    
      } else if (times === "三天内"&&workDayCount===3) {
        newTime.push(newClass[i])
          console.log("3")
       
      } else if (times === "一周内"&&workDayCount===7) {
        newTime.push(newClass[i])
          console.log("7")
         
      }
      else  {
          console.log("全部时间")
          console.log(newClass[i])
          newTime.push(newClass[i])
      }
    }
    console.log(newTime)
    setDateList(newTime)
    newTime=[]
    console.log(newTime)
  };
  //编辑表格的函数
  const changeDate = (record) => {
    console.log(record);
    // setDelDates(record);
    navigate("/HomePage/ChangeGg",{state:record});
  };
  const delDate = (record) => {
    console.log(selectedRowKeys)
    setDelArrId(record.id);
    console.log(record)
   if(selectedRowKeys.length===0){
    messageApi.info("没有选择删除的数据!");
   }else{
    setIsModalOpen(true);
   }
    
    setDelDates(record);
  };

  //表格///
  const [dataList, setDateList] = useState([]);
  // const data = [
  //   {
  //     id: 0,
  //     name: "夏季大促销1",
  //     position: "首页轮播1",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-201",
  //     state: "线上",
  //     num: "101",
  //   },
  //   {
  //     id: 1,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  //   {
  //     id: 2,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  //   {
  //     id: 3,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  //   {
  //     id: 4,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  //   {
  //     id: 5,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  //   {
  //     id: 6,
  //     name: "夏季大促销",
  //     position: "首页轮播",
  //     pc: "../../../src/static/image/32bb5f3c9f7b1bf6f1e718cc90c8fc9b.jpeg",
  //     time: "2021-3-20",
  //     state: "线上",
  //     num: "10",
  //   },
  // ];
  const columns = [
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "广告名称",
      dataIndex: "title",
      key: "title",
      width: 120,
    },
    {
      title: "广告位置",
      dataIndex: "position",
      key: "position",
      width: 120,
    },
    {
      title: "广告图片",
      key: "pc",
      width: 60,
      render: (_, record) => (
        <Space size="middle">
          <img
            style={{ width: "52px", height: "52px" }}
            src={"/api" + record.src}
            alt=""
          />
        </Space>
      ),
    },
    {
      title: "时间",
      dataIndex: "startTime",
      key: "startTime",
      width: 150,
    },
    {
      title: "线上/线下",
      dataIndex: "class",
      key: "class",
      width: 80,
    },
    {
      title: "点击次数",
      dataIndex: "number",
      key: "number",
      width: 60,
    },
    {
      title: "操作",
      key: "num",
      render: (_, record) => (
        <Space size="middle">
          <button
            type=""
            onClick={() => {
              changeDate(record);
            }}
            style={{
              width: "50px",
              backgroundColor: "white",
              border: "0px",
              color: "#00d1ff",
            }}
          >
            编辑
          </button>
          <button
            type=""
            onClick={() => {
              delDate(record);
            }}
            style={{
              width: "50px",
              backgroundColor: "white",
              border: "0px",
              color: "#00d1ff",
            }}
          >
            删除
          </button>
        </Space>
      ),
      width: 60,
    },
  ];
  //   setDateList();
  //多少页
  const [pageNmu, setPageNmu] = useState("");
  //页的余数
  const [pageYU, setPageYu] = useState("");
  
  useEffect(() => {
    axios({
      url: "/advertisement",
      method: "post",
    })
      .then((res) => {
        // console.log("获取所有学生数据", res);

        if (res.status === 200) {
          setDateList(res.data.data);
          setdatas(res.data.data)
          // console.log(res.data.data.length)
          let num = Math.floor(res.data.data.length / 5);
          let yushu = res.data.data.length % 5;
          // console.log(num,yushu)
          setPageNmu(num);
          setPageYu(yushu);
        }
      })
      .catch((err) => {
        console.log("获取所有学生数据1111", err);
      });
    // console.log(11)
    // setDateList(data);
    // console.log(data)

    // console.log(num + "--------------", yushu);
  }, []);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);

    setIdarr(newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  //
  const [currents, setCurrents] = useState(1);

  //单选框数据,表格下面的全选按钮
  const [RadioState, setRadioState] = useState(false);

  const changeRadio = () => {
    let end = 5 * currents - 1;
    let start;
    if (currents > 1) {
      start = end - 4;
    } else {
      start = 0;
    }
    console.log(start, end);

    //通过下标拿id
    let arr = [];
    let datas = [];
    if (pageNmu >= currents) {
      for (let i = start; i <= end; i++) {
        arr.push(dataList[i].id);
      }
    } else if (pageNmu < currents) {
      for (let i = start; i <= end; i++) {
        datas.push(i);
      }
      console.log(datas);
      console.log(pageYU);
      let dataIndex = [];
      for (let i = 0; i < pageYU; i++) {
        dataIndex.push(datas[i]);
      }
      console.log(dataIndex);
      for (
        let i = dataIndex[0];
        i <= dataIndex[0] + dataIndex.length - 1;
        i++
      ) {
        arr.push(dataList[i].id);
      }
    }

    console.log(arr);
    if (RadioState === false) {
      setRadioState(true);
      // setSelectedRowKeys([1, 17, 18]);
      onSelectChange([...arr]);
    } else {
      setRadioState(false);
      setSelectedRowKeys([]);
      onSelectChange([]);
    }
  };
  const getPage = (e) => {
    // console.log(dataList.length);
    setRadioState(false);
    setCurrents(e.current);
    // console.log(e.current);
  };
  //批量操作
  const [czState, setCzState] = useState("");
  const plcz = (value) => {
    setCzState(value);
  };
  //确定批量操作
  const qd = () => {
    console.log(selectedRowKeys);
    if (selectedRowKeys.length === 0) {
      console.log(0);

      messageApi.info("没有选择删除的数据!");
    } else {
      if (czState === "") {
        console.log(11);
        messageApi.info("没有选择相应的操作!");
      } else if (czState === "上线"||czState === "下线") {
        console.log(idArr);
        axios({
          url: "/adAnyStatus",
          method: "post",
          data: {
            idArr: idArr,
            status:czState,
          },
        })
          .then((res) => {
        
            if (res.status === 200) {
              axios({
                url: "/advertisement",
                method: "post",
              })
                .then((res) => {
                  // console.log("获取所有学生数据", res);
          
                  if (res.status === 200) {
                    setDateList(res.data.data);
                    setdatas(res.data.data)
                    // console.log(res.data.data.length)
                    let num = Math.floor(res.data.data.length / 5);
                    let yushu = res.data.data.length % 5;
                    // console.log(num,yushu)
                    setPageNmu(num);
                    setPageYu(yushu);
                  }
                })
                .catch((err) => {
                  console.log("获取所有学生数据1111", err);
                });
              messageApi.info("修改成功!");
              
            } else {
              messageApi.info("修改失败!");
            }
          })
          .catch((err) => {
            console.log(err);
            messageApi.info("删除失败!");
          });
      
      } else if (czState === "删除") {
        let arr = [...dataList];
        for (let i = 0; i <= arr.length - 1; i++) {
          if (arr[i].id === delArrId) {
            arr.splice(i, 1);
          }
        }
        console.log(idArr);

        axios({
          url: "/adDel",
          method: "post",
          data: {
            idArr: idArr,
          },
        })
          .then((res) => {
            console.log(res);
            if (res.status === 200) {
              console.log(11111);
              let a = [...dataList];
              for (let i = 0; i <= a.length - 1; i++) {
                if (idArr.indexOf(a[i].id) !== -1) {
                  a.splice(i, 1);
                }
              }
              setDateList(a);
              messageApi.info("删除成功!");
            } else {
              messageApi.info("删除失败!");
            }
          })
          .catch((err) => {
            console.log(err);
            messageApi.info("删除失败!");
          });
      }
    }
  };
  //添加广告
  const navigate = useNavigate();
  const addGg = () => {
    console.log(111);
    navigate("/HomePage/AddGg");
  };
  // const hasSelected = selectedRowKeys.length > 0;
  return (
    <div
      style={{
        width: "100%",
        display: "flex",
        justifyContent: "center",
        flexDirection: "column",
        alignItems: "center",
        height: "95%",
      }}
    >
      <div
        style={{
          width: "97%",
          display: "flex",
          justifyContent: "flex-start",
          marginTop: "10px",
          zIndex: "999",
          backgroundColor: "white",
          //   border: "1px solid red",
          height: "8%",
        }}
      >
        <form
          style={{
            width: "100%",
            display: "flex",
            justifyContent: "flex-start",
          }}
        >
          <Input
            value={inputValue}
            onChange={(value) => {
              changeInput(value);
            }}
            placeholder="广告名称"
            style={{ width: "15%", marginRight: "1%", height: "33px" }}
          />
          <Select
            defaultValue="全部"
            style={{
              width: "15%",
              marginRight: "1%",
              textAlign: "left",
              height: "33px",
            }}
            onChange={swiperChange}
            options={[
              {
                value: "全部",
                label: "全部",
              },
              {
                value: "首页轮播",
                label: "首页轮播",
              },
              {
                value: "商城首页轮播",
                label: "商城首页轮播",
              },
            ]}
          />
          <Select
            defaultValue="全部时间"
            style={{
              width: "15%",
              marginRight: "1%",
              textAlign: "left",
              height: "33px",
            }}
            onChange={timeChange}
            options={[
              {
                value: "全部时间",
                label: "全部时间",
              },
              {
                value: "一天内",
                label: "一天内",
              },
              {
                value: "三天内",
                label: "三天内",
              },
              {
                value: "一周内",
                label: "一周内",
              },
            ]}
          />
          <Button
            type="primary"
            onClick={searchDate}
            style={{ width: "7%", marginRight: "1%", height: "33px" }}
          >
            查询
          </Button>
          <Button
            type="primary"
            
            onClick={getAllDate}
            style={{ width: "7%", marginRight: "1%", height: "33px",textAlign:"center",display:"flex",justifyContent:"center",alignItems:"center"}}
          >
            所有数据
          </Button>
          <Button
            type="primary"
            onClick={addGg}
            style={{
              width: "7%",
              marginRight: "1%",
              backgroundColor: "#ffffff",
              color: "black",
              border: "1px solid #cccccc",
              height: "33px",
            }}
          >
            添加广告
          </Button>
        </form>
      </div>
      <div
        className="table-div "
        style={{
          width: "97%",
          height: "90%",
          overflowY: "scroll",
          //   overflow: "hidden",
        }}
      >
        <Table
          rowKey={(record) => record.id}
          pagination={{ defaultPageSize: 5 }}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataList}
          onChange={(current) => {
            getPage(current);
          }}
        />
        <div
          className="btn"
          style={{ display: "flex", marginTop: "-50px", alignItems: "center",marginLeft:"100px" }}
        >
          <Radio
            checked={RadioState}
            onClick={changeRadio}
            style={{ marginLeft: "15px", borderRadius: "0px" }}
          >
           <span style={{marginLeft:"-30px"}}> 全选</span>
          </Radio>
          <Select
            defaultValue="批量操作"
            style={{
              marginRight: "1%",
              textAlign: "left",
              height: "33px",
              marginLeft:"-20px"
            }}
            onChange={plcz}
            options={[
              {
                value: "上线",
                label: "上线",
              },
              {
                value: "下线",
                label: "下线",
              },
              {
                value: "删除",
                label: "删除",
              },
            ]}
          />
          <Button
            className="but"
            type="primary"
            onClick={qd}
            style={{
              width: "80px",
              height: "33px",
              textAlign: "center",
              backgroundColor: "white",
              marginLeft:"10px",
              color: "black",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              // backgroundColor:"#1677ff"
            }}
          >
            确定
          </Button>
        </div>
      </div>
      {contextHolder}
      <Modal
        title="确认提示"
        okText="确认"
        cancelText="取消"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        style={{ marginTop: "10%", overflow: "hidden" }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
          }}
        >
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              marginBottom: "20px",
            }}
          >
            <ExclamationCircleOutlined
              style={{ fontSize: "30px", color: "red", marginRight: "10px" }}
            />
            <span style={{ fontWeight: 800, fontSize: "20px" }}>系统提示</span>
          </div>
          <span>确定删除该条广告的消息吗？</span>
          <hr
            style={{
              width: "120%",
              border: "#e4e4e4 1px solid",
              marginTop: "20px",
              marginLeft: "-10%",
            }}
          ></hr>
        </div>
      </Modal>
    </div>
  );
};
export default Advertisement;
